<template>
    <div class="row end cross-start">
        <div ref="refScratch" style="position: absolute; width: 100%; height: 100%; top: 0px"></div>
    </div>
</template>

<script lang="ts" setup>
import {ref, reactive, onMounted} from 'vue'
import scratch3 from "./scratch"
import { AppModel } from '../../../model/AppModel'
import { bus } from '../@beshell/events-ts/bus';

const refScratch = ref(null)
let model:AppModel

let hasInitScratch = false

onMounted(function () {
    console.log("program mounted")
})


function enter() {
    if(hasInitScratch) {
        return
    }
    
    hasInitScratch = true

    scratch3.init(refScratch.value, bus)

    if(model) {
        loadModel(model)
    }
}
function leave() {

}

function serialize() {
    var doc = Blockly.Xml.workspaceToDom(scratch3.workspace)
    var data = Blockly.Xml.domToText(doc)
    return data
}


function setModel(_model: AppModel) {

    model = _model
    
    if(scratch3.workspace) {
        scratch3.workspace.clear()
    }

    if(hasInitScratch && _model){
        loadModel(_model)
    }
}

function loadModel(model:AppModel) {
    if(model.blocklyXML) {
        var xml = Blockly.Xml.textToDom(model.blocklyXML);
        try{
            Blockly.Xml.clearWorkspaceAndLoadFromXml(xml, scratch3.workspace);
        }catch(e){
            console.error(e)
        }
        scratch3.vm.runtime.model = model
    }
    else {
        if(scratch3.workspace)
            scratch3.workspace.clear()
    }
}

defineExpose({
    enter, setModel, serialize, leave
})
</script>